//
//  ClubDynamicDetailViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/30.
//

import UIKit
import ZLPhotoBrowser

private let headerID    = "ClubDynamicDetailHeaderView"

class ClubDynamicDetailViewController: ClubBaseViewController, RaeAnimationProtocol {
    
    private var navView = ClubDynamicDetailNavView()
    private var bottomView = ClubDynamicDetailBottomView()
    private let commitView = ClubDynamicDetailommitView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubDynamicDetailCell.self,ClubDynamicDetailommitCell.self,ClubDynamicDetailCommitEmptyCell.self)
        tableView.register(ClubDynamicDetailHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        tableView.separatorColor = .clear
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return tableView
    }()
    
    
    var dynamicID: String = "" {
        didSet{
            loadData()
            loadCommitList()
        }
    }
    private var pageIndex = 1
    private var isLook = ""
    private var model: ClubGameCircleModel?
    private var commitData: [ClubDynamicDetailCommentModel]?
    private var isLoadLikeState = false
    private var pid = ""
    
    var updateDataBlock: (() -> Void)?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.post(name: .stopDetailAudioPlayer, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            navView
            tableView
            bottomView
            commitView
        }
        
        navView.leading(0).trailing(0).top(0).height(.navi_height)
        tableView.leading(0).trailing(0).top(.navi_height).bottom(.tabBar_height)
        bottomView.leading(0).trailing(0).height(.tabBar_height).bottom(0)
        commitView.leading(0).width(.screenWidth).height(47.0.Scale).bottom(0)
        
        commitView.isHidden = true
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        navView.backBlock = {
            self.navigationController?.popViewController(animated: true)
        }
        navView.shareBlock = {
            let moreView = ClubMoreView()
            moreView.uid_des = self.model?.uid_des ?? ""
            moreView.reportBlock = {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    let reportVC = ClubReportViewController()
                    reportVC.dynamicID = self.model?.id ?? ""
//                    reportVC.updateDataBlock = {
//                        self.navigationController?.popViewController(animated: true)
//                    }
                    self.present(reportVC, animated: true)
                }else{
                    //登录
                    self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                }
            }
            moreView.delBlock = {
                Task{
                    let res = await self.network.request(.delDynamic(id: self.model?.id ?? ""))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.updateDataBlock?()
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type)
            }
            self.entryAnimate.animation(show: moreView)
        }
        navView.userBlock = { uid in
            if uid.count > 0 {
                if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                    let otherVC = ClubMineInfoViewController()
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }else{
                    let otherVC = ClubOtherInfoViewController()
                    otherVC.uid = uid
                    otherVC.isDetailFrom = true
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }
            }            
        }
        
        bottomView.likeBlock = {
            self.likeAction(type: "0", id: self.dynamicID)
        }
        bottomView.commitBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        bottomView.shareBlock = {
            let moreView = ClubForumShareView()
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type)
            }
            self.entryAnimate.animation(show: moreView)
        }
        commitView.sendTextBlock = { text in
            self.sendCommit(text: text)
        }
         
//        NotificationCenter.default.addObserver(self, selector: #selector(commitSonLike), name: .likeSonCommit, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    private func shareDetail(type: Int) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.dynamicShareTitle, description: ClubGlobalTool.shared.dynamicShareDes, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: self.model?.share_url ?? "")
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            let shareUrl = self.model?.share_url ?? ""
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.dynamicShareTitle, des: ClubGlobalTool.shared.dynamicShareDes, image: "AppIcon".toImage!, shareUrl: self.model?.share_url ?? "", shareType: type)
        }
    }
}

extension ClubDynamicDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {

        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 1 {
            if self.commitData?.count ?? 0 > 0 {
                return self.commitData?.count ?? 0
            }else{
                return 1
            }
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
            
            if self.commitData?.count ?? 0 == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailCommitEmptyCell", for: indexPath) as! ClubDynamicDetailCommitEmptyCell
                cell.commitBlock = {
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                        self.bottomView.isHidden = true
                        self.commitView.isHidden = false
                        self.commitView.commitView.becomeFirstResponder()
                    }else{
                        //登录
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                    }
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailommitCell", for: indexPath) as! ClubDynamicDetailommitCell
                cell.detailCommit = self.commitData?[indexPath.row]
                cell.showMoreView = { commitId, uid in
                    self.commitShare(commitID: commitId, uid: uid)
                }
                return cell
            }
            
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailCell", for: indexPath) as! ClubDynamicDetailCell
        cell.model = model
//        cell.likeBlock = {
//            self.likeAction(type: "0", id: self.dynamicID)
//        }
        cell.toGameDetailVC = { gid in
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = gid
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.toTopicDetailVC = { topicId in
            let detailVC = ClubTopicDetailViewController()
            detailVC.topicId = topicId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            if indexPath.row == 0 {
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }else{
                if self.commitData?.count ?? 0 != 0 {
                    let model = self.commitData?[indexPath.row - 1]
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                        self.bottomView.isHidden = true
                        self.commitView.isHidden = false
                        let user_name = model?.pet_name ?? ""
                        self.pid = model?.id ?? ""
                        self.commitView.commitView.placeHolder = "回复\(user_name)"
                        self.commitView.commitView.becomeFirstResponder()
                    }else{
                        //登录
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                    }
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if let commitArray = self.commitData, commitArray.count > 0 && section == 1 {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubDynamicDetailHeaderView
            header.titleString = "(\(commitArray.count))"
            return header
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if let commitArray = self.commitData, commitArray.count > 0 && section == 1 {
            return 44.0.Scale
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 1 && self.commitData?.count ?? 0 > 0 && indexPath.row > 0{
            
            guard let md = self.commitData?[indexPath.row - 1] else { return 0.0 }
            var tableViewH = 0.0
            if let arr = md.data, arr.count > 0 {
                tableViewH = self.calculateHeight(dataArray: arr)
            }
            let height = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 104.0.Scale) + 99.0.Scale + tableViewH + 12.0.Scale
            return height
        }
        
        return UITableView.automaticDimension
    }
    
    private func calculateHeight(dataArray: [ClubDynamicDetailCommentModel]) -> CGFloat{
        
        var height = 0.0
        for md in dataArray {
            height += 32.0.Scale
            let contentH = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 138.0.Scale) + 34.0
            height += contentH
        }
        return height
    }
}


//MARK: action
extension ClubDynamicDetailViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func likeAction(type: String, id: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            //点赞
            Task {
                let models = await network.request(.dynamicLike(type: type, dynamicID: id),isShowError: false)
                if models.isSuccess {
                    self.updateDataBlock?()
                    self.isLook = "1"
                    if type == "1" {
                        self.loadNewData()
                    }else{
                        self.isLoadLikeState = true
                        self.loadData()
                    }
                }
            }
        }else{
            //登录
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func commitSonLike(_ noti: Notification){
        
        if let id = noti.userInfo?["id"] as? String {
            likeAction(type: "1", id: id)
        }
    }
    
    private func commitShare(commitID: String, uid: String){
        let moreView = ClubGameMoreView()
        moreView.uid_des = uid
        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = commitID
                reportVC.type = "2"
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.delBlock = {
            Task{
                let res = await self.network.request(.delDynamicCommit(commitID: commitID))
                if res.isSuccess {
                    "删除成功".toast_success
                    self.loadNewData()
                }
            }
        }

        self.entryAnimate.animation(show: moreView)
    }
    
    // 键盘消失时调用的方法
    @objc func keyboardWillHide(_ notification: Notification) {
        guard let userInfo = notification.userInfo else { return }

        self.commitView.isHidden = true
        self.bottomView.isHidden = false
    }
}


//MARK: network
extension ClubDynamicDetailViewController {
    
    private func loadData(){
        
        Task{
            ToastUtil.show()
            let models = await network.request(.dynamicDetail(is_look: isLook, dynamicID: dynamicID),type:ClubGameCircleModel.self)
            ToastUtil.dismiss()
            if models.isSuccess, let model = models.model {
                    
                self.navView.model = model
                self.bottomView.model = model
                self.model = model
                if !isLoadLikeState{
                    tableView.reloadData()
                }
                self.isLoadLikeState = false
            }
        }
    }
    
    private func loadCommitList(){
        Task{
            let models = await network.request(.dynamicCommitList(dynamicID: self.dynamicID, page: pageIndex),type:ClubDynamicDetailCommentModel.self)
            tableView.refresh_end()
            if models.isSuccess, let models = models.models {
                self.commitData = models
                tableView.reloadSections(IndexSet(integer: 1), with: .automatic)
//                tableView.reloadData()
            }
        }
    }
    
    private func loadNewData(){
        pageIndex = 1
        loadCommitList()
    }
    
    private func loadMoreData(){
        pageIndex += 1
        Task{
            let models = await network.request(.dynamicCommitList(dynamicID: self.dynamicID, page: pageIndex),type:ClubDynamicDetailCommentModel.self)
            tableView.refresh_end()
            if models.isSuccess, let models = models.models {
                self.commitData?.append(contentsOf: models)
//                tableView.reloadData()
                tableView.reloadSections(IndexSet(integer: 1), with: .automatic)
            }
        }
    }
    
    private func sendCommit(text: String){
        Task{
            let models = await network.requestSpecial(.dynamicCommit(dynamicID: self.dynamicID, pid: self.pid, content: text))
            if models.isSuccess {
                
                "评论成功".toast_success
                self.loadNewData()
                self.commitView.commitView.text = ""
                self.commitView.commitView.placeHolder = "写点什么..."
                self.pid = ""
                self.updateDataBlock?()
                self.commitView.commitView.resignFirstResponder()
            }else{
                models.errorMessage?.toast_error
            }

        }
    }
}
